package com.starinside.wp.controller.api.Template;


import lombok.Data;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Data
public class PushEvent {

    // 评测报告
    public static final int EVENTTYPE_EVOLUATION = 1;

    // 签到消息
    public static final int EVENTTYPE_CHECKIN = 2;

    // 签退消息
    public static final int EVENTTYPE_CHECKOUT = 3;

    // 通知
    public static final int EVENTTYPE_NOTICE = 4;

    // 推广消息
    public static final int EVENTTYPE_AD = 5;

    //
    public static final int EVENTTYPE_MAX = 5;


    // 推送范围
    public static final int NOTIFY_USER = 0;
    public static final int NOTIFY_ALL = 1;


    // 推送状态
    public static final int STATUS_SUCCESS = 0;
    public static final int STATUS_BAD_TYPE = -1;
    public static final int STATUS_MIS_OPENID_WP = -2;
    public static final int STATUS_INVALID_USER_MOBILE = -3;
    /**
     * 事件类型
     */
    private int eventType;

    /**
     *
     */
    private int objectId;

    /**
     *  群体通知, 跟 userMobile 二选一
     */
    private int notifyGroup;

    /**
     * 特定用户的手机号码
     */
    private String userMobile;

    /**
     * 关联的宝宝名字
     */
    private String nickname;

    /**
     * 关联报告 url
     */
    private String refUrl;


    private String sign;


    public void SignEvent(){
        sign = calcSignStr();
    }

    private String calcSignStr(){
        String base = "{" +
                "userMobile='" + userMobile + '\'' +
                ", eventType='" + eventType + '\'' +
                ", nickname='" + nickname + '\'' +
                ", refUrl='" + refUrl + '\'' +
                ", objectId=" + objectId +
                ", notifyGroup=" + notifyGroup +
                '}' + "lovinf";

        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] hashInBytes = md.digest(base.getBytes(StandardCharsets.UTF_8));

        StringBuilder sb = new StringBuilder();
        for (byte b : hashInBytes) {
            sb.append(String.format("%02x", b));
        }

        String result = sb.toString();

        return result;
    }

    public Boolean CheckedSign(){
        String result = calcSignStr();
        System.out.println("checking push sign " + result + " vs " + sign);
        return result.equals(sign);
    }

    @Override
    public String toString() {
        return "WxTemplate{" +
                "userMobile='" + userMobile + '\'' +
                ", eventType='" + eventType + '\'' +
                ", nickname='" + nickname + '\'' +
                ", refUrl='" + refUrl + '\'' +
                ", objectId=" + objectId +
                ", notifyGroup=" + notifyGroup +
                '}';
    }
}
